package logic

import (
	"context"
	"encoding/json"
	"github.com/Baidu-AIP/golang-sdk/aip/censor"
	"github.com/olivere/elastic/v7"
	"month/videosvr/internal/service"
	"month/videosvr/internal/svc"
	"month/videosvr/video"

	"github.com/zeromicro/go-zero/core/logx"
)

type EsSearchLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewEsSearchLogic(ctx context.Context, svcCtx *svc.ServiceContext) *EsSearchLogic {
	return &EsSearchLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// todo 视频搜索
func (l *EsSearchLogic) EsSearch(in *video.EsSearchReq) (*video.EsSearchRes, error) {
	// todo: add your logic here and delete this line
	//todo  敏感词过滤
	client := censor.NewClient("i7GMCPKC5KW1oox4QGUWIWzd", "RYRWeQoUmfvsHQzWtBY2INqG2QUudtIz")
	censorRes := client.TextCensor(in.Word)
	var censorMap map[string]interface{}
	json.Unmarshal([]byte(censorRes), &censorMap)
	if censorMap["conclusion"] == "不合规" {
		return &video.EsSearchRes{
			Data:      nil,
			Page:      0,
			CountPage: 0,
		}, nil
	}
	//todo 查询条件
	query := elastic.NewBoolQuery()
	if in.Word == "" {
		query.Should(
			elastic.NewMatchAllQuery(),
		)
	} else {
		query.Should(
			elastic.NewMatchQuery("video_title", in.Word),
			elastic.NewMatchQuery("sub_title", in.Word),
		)
	}
	//todo 高亮显示
	high := elastic.NewHighlight()
	text := elastic.NewHighlighterField("video_title").PreTags("<span style=\"color:'red'\">").PostTags("</span>")
	textOne := elastic.NewHighlighterField("sub_title").PreTags("<span style=\"color:'red'\">").PostTags("</span>")
	high.Fields(textOne, text)
	//todo es分页查询
	page, countPage, res, err := service.EsSearch(in.Index, query, high, int(in.Page))
	if err != nil {
		return &video.EsSearchRes{
			Data:      nil,
			Page:      0,
			CountPage: 0,
		}, nil
	}
	list := service.EsList(res.(*elastic.SearchResult))
	return &video.EsSearchRes{
		Data:      list,
		Page:      int64(page),
		CountPage: int64(countPage),
	}, nil
}
